//
//  ViewController.swift
//  jisuan
//
//  Created by safeu on 2017/9/27.
//  Copyright © 2017年 xuyuanyuan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var display: UILabel!
    var shuru = false
    var style = ""
    
    @IBAction func number(_ sender: UIButton) {
        let digit = sender.currentTitle
        if shuru {
            display.text = display.text! + digit!
        }else{
            display.text = digit
            shuru = true
        }
    }
    var operandStack: Array<Double> = Array<Double>()
    @IBAction func enter() {
        shuru = false
        operandStack.append(displayValue)
        switch style {
        case "*":performOperation(operation: multply)
        case "／":performOperation(operation: subtraction)
        case "+":performOperation(operation: multiplication)
        case "-":performOperation(operation: division)
        default:
            break
        }
    }
    func multply(op1: Double , op2: Double) -> Double {
        return op1*op2
    }
    func subtraction(op1: Double , op2: Double) -> Double {
        return op2 / op1
    }
    func multiplication(op1: Double , op2: Double) -> Double {
        return op1 + op2
    }
    func division(op1: Double , op2: Double) -> Double {
        return op2 - op1
    }
    var displayValue:Double{
        get{
            return NumberFormatter().number(from: display.text!)!.doubleValue
        }
        set{
            display.text = "\(newValue)"
            shuru = false
        }
    }
    @IBAction func operate(_ sender: UIButton) {
        shuru = false
        operandStack.append(displayValue)
        style = sender.currentTitle!
    }
    func performOperation(operation: (Double,Double)->Double) {
        if operandStack.count >= 2 {
            displayValue = operation(operandStack.removeLast(),operandStack.removeLast())
        }
    }
    @IBAction func acBtn() {
        operandStack.removeAll()
        display.text = "0"
        shuru = false
    } 
}

